package clientServlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.*;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

import controller.Controller;
import dataBase.Ad;
import dataBase.Business;


@SuppressWarnings("serial")
public class ShowAdClient extends HttpServlet {
	private static int defaultWidth = 200;
	private static int defaultHeight = 200;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		System.out.println("show image");
		String clientUserName = (String) req.getSession().getAttribute("userNameClient");
		String key = (String)req.getParameter("id");
		printImage(key,req.getParameter("width"),req.getParameter("height"),resp.getOutputStream());

	}
	
	private void printImage(String key, String stringWidth,String stringHeight, ServletOutputStream servletOutputStream)
	{
		 if(key != null) 
		    { 
		        long id = Long.parseLong(key);
			 	Ad ad = Controller.getInstance().keyToAd(id);
		 	
		        if (ad==null || ad.getAdPic()==null)
		        {
		        	System.out.println("no ad image to show");
		        	return;
		        }
		        Controller.getInstance().adAppeared(id);
		        byte[] imageBytes = ad.getAdPic().getBytes();
		        
		        //show the image
		        if (imageBytes!=null)
		        {
		    		
		    		int intWidth = defaultWidth;
		    		int intHeight = defaultHeight;
		    		
		    		if (stringWidth!=null)
		    			intWidth = Math.min(Integer.parseInt(stringWidth),ImagesService.MAX_RESIZE_DIMENSIONS);
		    		
		    		if (stringHeight!=null)
		    			intHeight = Math.min(Integer.parseInt(stringHeight),ImagesService.MAX_RESIZE_DIMENSIONS);
		    		
		    		System.out.println(intWidth + " "+ intHeight);
		        	Image oldImage = ImagesServiceFactory.makeImage(imageBytes);
		        	ImagesService isService = ImagesServiceFactory.getImagesService();
					Transform tfrm = ImagesServiceFactory.makeResize(intWidth,intHeight);
					Image newImage = isService.applyTransform(tfrm, oldImage);
					
					try {
						servletOutputStream.write(newImage.getImageData());
					} catch (IOException e) {
						e.printStackTrace();
					}
					
		        }
		        else
		        	System.out.println("no ad image to show");
		    } 

		
	}
	

}
